package com.atguigu.sql;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

public class SqlStreamDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<WaterSensor> sourceDs = env.fromElements(
                new WaterSensor("s1", 1L, 1),
                new WaterSensor("s1", 2L, 2),
                new WaterSensor("s2", 2L, 2),
                new WaterSensor("s3", 3L, 3),
                new WaterSensor("s3", 4L, 4)
        );

        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        // TODO 1. 流转表
        tableEnv.createTemporaryView("sensor1", sourceDs);
        Table table = tableEnv.fromDataStream(sourceDs);
        tableEnv.createTemporaryView("sensor", table);
        table.execute().print();

        // TODO 2. 表转流
        Table filterTable = tableEnv.sqlQuery("select * from sensor where vc > 2");
        // 2.2 changelog流(结果需要更新)
        DataStream<WaterSensor> dataStream = tableEnv.toDataStream(filterTable, WaterSensor.class);
        dataStream.print();

        Table ctTable = tableEnv.sqlQuery("select id, count(id) as cnt from sensor group by id");
        // 2.2 changelog流(结果需要更新)
        DataStream<Row> changelogStream = tableEnv.toChangelogStream(ctTable);
        changelogStream.print();

        env.execute();
    }
}
